package com.atguigu.crowd.config;

import com.atguigu.crowd.entity.Admin;
import com.atguigu.crowd.entity.Role;
import com.atguigu.crowd.service.api.AdminService;
import com.atguigu.crowd.service.api.AuthService;
import com.atguigu.crowd.service.api.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * SpringSecurity 用户信息服务
 * 用于登录和获取角色和权限
 *
 * @author Chan
 * @since 2022/9/26
 */
@Component
public class CrowdfundingUserDetailsService implements UserDetailsService {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private AuthService authService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据账号名查Admin对象
        Admin admin = adminService.getAdminByLoginAcct(username);
        Integer adminId = admin.getId();

        // 根据adminId查询角色和权限
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        List<Role> roleList = roleService.getAssignRoleList(adminId);
        for (Role role : roleList) {
            String roleName = role.getName();
            authorities.add(new SimpleGrantedAuthority("ROLE_" + roleName));
        }

        List<String> authNameList = authService.getAuthListByAdminId(adminId);
        for (String authName : authNameList) {
            authorities.add(new SimpleGrantedAuthority(authName));
        }

        // 封装admin和authorities到user的子类对象中
        return new SecurityAdmin(admin, authorities);
    }
}
